#!/bin/bash

BUILD_DIR="./build"
PROGRAM_PREFIX="sdv_test_"

if [ ! -d "$BUILD_DIR" ]; then
    echo "❌ Error: build directory not found."
    exit 1
fi

cd "$BUILD_DIR" || exit 1

PROGRAMS=$(find . -maxdepth 1 -type f -executable -name "${PROGRAM_PREFIX}*")
TOTAL=$(echo "$PROGRAMS" | wc -w)
COUNT=0

if [ "$TOTAL" -eq 0 ]; then
    echo "⚠️ No executables matching '${PROGRAM_PREFIX}*' found."
    exit 0
fi

echo "🔍 Running valgrind memory check on $TOTAL programs..."
echo

for prog in $PROGRAMS; do
    COUNT=$((COUNT + 1))
    PROG_NAME=$(basename "$prog")

    printf "▶️ [%2d/%2d] %-25s ... " "$COUNT" "$TOTAL" "$PROG_NAME"

    if [ ! -x "$prog" ]; then
        echo "❌ Not executable or missing"
        continue
    fi

    VALGRIND_OUT=$(valgrind --leak-check=summary --errors-for-leak-kinds=definite ./"$PROG_NAME" 2>&1)
    VALGRIND_STATUS=$?

    if [ $VALGRIND_STATUS -ne 0 ]; then
        echo "❌ Valgrind error or program crashed"
        continue
    fi

    DEF_LOST_LINE=$(echo "$VALGRIND_OUT" | grep "definitely lost")
    IND_LOST_LINE=$(echo "$VALGRIND_OUT" | grep "indirectly lost")

    if [ -z "$DEF_LOST_LINE" ] && [ -z "$IND_LOST_LINE" ]; then
        echo "✅ No memory leaks"
        continue
    fi

    if [ -z "$DEF_LOST_LINE" ]; then
        DEF_LOST_LINE="definitely lost: unknown"
    fi
    if [ -z "$IND_LOST_LINE" ]; then
        IND_LOST_LINE="indirectly lost: unknown"
    fi

    if [[ "$DEF_LOST_LINE" == *"0 bytes in 0 blocks"* && "$IND_LOST_LINE" == *"0 bytes in 0 blocks"* ]]; then
        echo "✅ No memory leaks"
    else
        echo "⚠️ Memory leaks detected:"
        echo "   $DEF_LOST_LINE"
        echo "   $IND_LOST_LINE"
    fi

done

echo
echo "✅ All programs checked."
